
#include "spi-driver.h"

uint8_t tx_buffer[128];
uint8_t rx_buffer[128];

// Perform SPI transfer
struct spi_ioc_transfer transfer = {
    .delay_usecs = 0,
    .speed_hz = 49000000,  // SPI speed in Hz 1MHz
    .bits_per_word = 8,
};

int SPI_Open(void)
{
    int spi_file;
    // Open the SPI device
    if ((spi_file = open(SPI_DEVICE_PATH, O_RDWR)) < 0) {
        perror("Failed to open SPI device");
        return -1;
    }
    // Configure SPI mode and bits per word
    uint8_t mode = SPI_MODE_0;
    uint8_t bits = 8;
    if (ioctl(spi_file, SPI_IOC_WR_MODE, &mode) < 0) {
        perror("Failed to set SPI mode");
        close(spi_file);
        return -1;
    }
    if (ioctl(spi_file, SPI_IOC_WR_BITS_PER_WORD, &bits) < 0) {
        perror("Failed to set SPI bits per word");
        close(spi_file);
        return -1;
    }
    return spi_file;
}

int SPI_Transfer(int spi_file,uint8_t *tx_data, uint16_t len)
{
    transfer.tx_buf = (unsigned long)tx_data;
    transfer.len = len;
    int ret = ioctl(spi_file, SPI_IOC_MESSAGE(1), &transfer);
    if (ret < 0) {
        perror("Failed to transfer data");
        close(spi_file);
        return -1;
    }
    return 0;
}

int SPI_Receive(int spi_file, uint8_t *rx_data, uint16_t len)
{
    transfer.rx_buf = (unsigned long)rx_data;
    transfer.len = len;
    int ret = ioctl(spi_file, SPI_IOC_MESSAGE(1), &transfer);
    if (ret < 0) {
        perror("Failed to receive data");
        close(spi_file);
        return -1;
    }
    return 0;
}

int SPI_Close(int spi_file)
{
    close(spi_file);
    return 0;
}

